<?php
/**
 * Created by PhpStorm.
 * User: 小蛮哼哼哼
 * Email: 243194993@qq.com
 * Date: 2023/3/22
 * Time: 17:01
 * motto: 现在的努力是为了小时候吹过的牛逼！
 */

declare(strict_types=1);


namespace App\Common\Business;

use App\Common\Lib\Log\Log;
use App\Common\Lib\Tree;
use App\Constants\ErrorCode;
use App\Exception\FooException;
use App\Model\GoodsCategory;

class GoodsCategoryBusiness extends BusBase
{
    protected $obj_model;

    public function __construct()
    {
        $this->obj_model = new GoodsCategory();
    }


    /**
     * @param array $data
     * @return true
     */
    public function add(array $data = []): bool
    {
        $insert_data = [
            "title" => $data['title'],
            "sort" => $data['sort'],
            "logo" => $data['logo'],
            "parent_id" => $data['parent_id']
        ];
        if (!empty($insert_data['parent_id'])) {
            if (empty($insert_data['logo'])) {
                throw new FooException("请选择logo图片");
            }
        }
        try {
            if (!empty($insert_data['parent_id'])) {
                $insert_data['parent_id'] = end($insert_data['parent_id']);
            } else {
                $insert_data['parent_id'] = 0;
            }
            if (empty($data['id']) || $data['id'] == 0) {
                $insert_data['create_time'] = time();
                $insert_data['update_time'] = time();
                $result = $this->obj_model
                    ->insert($insert_data);
            } else {
                $result = $this->obj_model->where('id', $data['id'])
                    ->update($insert_data);
            }
        } catch (\Exception $e) {
            Log::get('get' . $this->obj_model . "index", 'error')->error($e->getMessage());
            throw new FooException("查询失败" . $e->getMessage());
        }
        if (!$result) {
            throw new FooException("操作失败");
        }
        return true;
    }

    /**
     * 获取分类列表
     * @return mixed[]
     */
    public function getGoodsCategoryByList(): array
    {
        try {
            $result = $this->obj_model->where('status', ErrorCode::MYSQL_SUCCESS)
                ->where('parent_id', 0)
                ->orderBy('sort', "desc")
                ->orderBy('id', 'desc')
                ->get(["id", "logo", "title", "parent_id", 'id as children'])->toArray();
        } catch (\Exception $e) {
            throw new FooException("查询失败" . $e->getMessage());
        }
        $lists = [];
        if (!empty($result)) {
            $lists = (new Tree())->arrayMenu($result, 0, 'parent_id', 'children');
        }
        return $lists;
    }

    /**
     * @return array
     */
    public function getGoodsCategoryThreeList(): array
    {
        try {
            $result = $this->obj_model->where('status', ErrorCode::MYSQL_SUCCESS)
                ->orderBy('sort', "desc")
                ->orderBy('id', 'desc')
                ->get(["id", "logo", "title", "parent_id"])->toArray();
        } catch (\Exception $e) {
            throw new FooException("查询失败" . $e->getMessage());
        }
        $lists = [];
        if (!empty($result)) {
            $lists = (new Tree())->arrayMenu($result, 0, 'parent_id', 'children');
        }
        return $lists;
    }

    /**
     * @param string $url
     * @return array
     */
    public function getGoodsCategoryIndexByList(string $url = ''): array
    {
        try {
            $result = $this->obj_model->where('status', ErrorCode::MYSQL_SUCCESS)
                //->where('parent_id', 0)
                ->orderBy('sort', 'desc')
                ->orderBy('id', 'desc')
                ->get(["id", "logo", "title", "parent_id"])
                ->toArray();
        } catch (\Exception $e) {
            throw new FooException("查询失败");
        }
        if (!empty($result)) {
            foreach ($result as $k => $v) {
                if (!empty($v['logo'])) {
                    $result[$k]['logo'] = $url . $v['logo'];
                }
            }
        }
        return (new Tree())->arrayMenu($result, 0, 'parent_id', 'children');
    }

    public function getOneToAll(int $id = 0)
    {
        try {
            $row = $this->obj_model
                ->where('id', $id)
                ->where('status', ErrorCode::MYSQL_SUCCESS)
                ->get(['id', 'title', 'parent_id'])
                ->toArray();
        } catch (\Exception $e) {
            throw new FooException("查询失败");
        }
        if (empty($row)) {
            throw new FooException("菜单数据不存在");
        }
        //查询所有的二级菜单
        try {
            $rr = $this->obj_model
                ->where('parent_id', $row[0]['parent_id'])
                ->where('status', ErrorCode::MYSQL_SUCCESS)
                ->get(['id', 'title', 'parent_id'])
                ->toArray();
        } catch (\Exception $e) {
            throw new FooException("查询失败");
        }

        $lists = [];
        if (!empty($rr)) {
            foreach ($rr as $k => $v) {
                $lists[$k] = $v;
                //查询所有
                $ret = $this->obj_model->where('parent_id', $v['id'])
                    ->where('status', ErrorCode::MYSQL_SUCCESS)
                    ->get(['id', 'title', 'parent_id'])
                    ->toArray();
                $lists[$k]['children'] = $ret;
            }
        }
        return $lists;
    }

    /**
     * @param int $limit
     * @param array $where
     * @param array $field
     * @param string $orderKey
     * @param string $order_value
     * @return array
     */
    public function index(int $limit = 10, array $where = [], array $field = ['*'], string $orderKey = 'id', string $order_value = 'desc'): array
    {
        $result = parent::index(100000000, $where, $field, $orderKey, $order_value);
        if (!empty($result['data'])) {
            $result['data'] = (new Tree())->arrayMenu($result['data'], 0, 'parent_id', 'children');
        }
        return $result;
    }
}